package com.bml.architect.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class EpollNIOServer {


    public static void main(String[] args) throws IOException {

        //打开一个serversocket
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        //绑定一个端口
        socketChannel.bind(new InetSocketAddress(8000));
        //设置为非阻塞
        socketChannel.configureBlocking(false);
        //打开Selector处理Channel，即创建epoll
        Selector selector = Selector.open();
        //将服务端的serverSocket注册到多路复用器selecctor上
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务启动成功...");
        while (true) {
            //阻塞，直到有新的事件（比如连接，读、写事件）
            selector.select();

            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey next = iterator.next();
                if (next.isAcceptable()) {
                    //连接事件
                    ServerSocketChannel ssc = (ServerSocketChannel) next.channel();
                    //接受一个连接SocketChannel
                    SocketChannel accept = ssc.accept();
                    accept.configureBlocking(false);
                    //这里只注册了读事件，如果需要给客户端发送数据可以注册写事件
                    accept.register(selector, SelectionKey.OP_READ);
                }
                if (next.isReadable()) {
                    //读取事件
                    SocketChannel sc = (SocketChannel) next.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int read = sc.read(buffer);
                    if (read > 0) {
                        System.out.println("读取客户端发过来的数据:" + new String(buffer.array(), 0, read));
                    } else if (read == -1) {
                        System.out.println("客户端关闭了连接");
                        sc.close();
                    }
                }
                //从事件集合里删除本次处理的key，防止下次select重复处理
                iterator.remove();
            }


        }


    }
}
